﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 管理员管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [Authorize]
    public class SystemInfoController : ControllerBase
    {
        IFreeSql db;
        public SystemInfoController(IFreeSql _db)
        {
            db = _db;
        }

        /// <summary>
        /// 查询管理员全部数据
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">条数</param>
        /// <param name="sysrealname">用户姓名</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInfo(int page, int limit, string? sysrealname)
        {
            var list = db.Select<Models.Systeminfo, Models.Roleinfo>()
                .LeftJoin((a, b) => a.Roleid == b.Roleid)
                .Where((a, b) => ((string.IsNullOrEmpty(sysrealname)) || (a.Sysrealname.Contains(sysrealname))) && (a.Isdelete != true))
                .Count(out var total)
                .Page(page, limit)
                .ToList((a, b) => new
                {
                    a.Sysid,
                    a.Sysname,
                    a.Sysrealname,
                    a.Syssex,
                    a.Sysimg,
                    a.Sysidcard,
                    a.Telephone,
                    a.Birthday,
                    a.Createtime,
                    a.Sysstate,
                    b.Roleid,
                    b.Rolename
                });
            var json = new
            {
                data = list,
                total = total,
                code = 200
            };
            return Ok(json);
        }

        /// <summary>
        /// 添加管理人员
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody] Models.Systeminfo info)
        {
            try
            {
                info.Createtime = DateTime.Now;
                info.Isdelete = false;
                info.Syspassword = "123456";
                int list = db.Insert(info).ExecuteAffrows();
                return Ok(list);
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }

        /// <summary>
        /// 修改管理人员
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update([FromBody] Models.Systeminfo info)
        {
            try
            {
                int list = db.Update<Models.Systeminfo>().SetSource(info).ExecuteAffrows();
                return Ok(list);
            }
            catch (Exception ex)
            {
                return Ok(false);
            }
        }

    }
}
